const { contextBridge, ipcRenderer } = require('electron');

// 添加调试日志
console.log('Preload script is running');

// 暴露安全的 API 到渲染进程
contextBridge.exposeInMainWorld('electron', {
  ipcRenderer: {
    send: (channel, ...args) => {
      // 白名单channels
      const validChannels = ['save-file', 'save-file-as'];
      if (validChannels.includes(channel)) {
        // 验证参数
        if (channel === 'save-file') {
          const [data] = args;
          if (!data || typeof data !== 'object' || !data.content) {
            console.error('Invalid save-file arguments:', args);
            return;
          }
        }
        console.log('Sending IPC message:', channel, args);
        ipcRenderer.send(channel, ...args);
      } else {
        console.warn('Invalid channel for send:', channel);
      }
    },
    on: (channel, func) => {
      // 白名单channels
      const validChannels = ['file-opened', 'save-file-reply', 'error'];
      if (validChannels.includes(channel)) {
        console.log('Registering IPC listener for channel:', channel);
        const subscription = (_event, ...args) => {
          console.log('Received IPC message on channel:', channel);
          console.log('Message args:', args);
          try {
            func(...args);
          } catch (error) {
            console.error('Error in IPC handler:', error);
          }
        };
        ipcRenderer.on(channel, subscription);
        return () => {
          console.log('Removing IPC listener for channel:', channel);
          ipcRenderer.removeListener(channel, subscription);
        };
      } else {
        console.warn('Invalid channel for on:', channel);
        return () => {};
      }
    }
  }
}); 